package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.Result;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    WorkspaceService workspaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<TurnoverReportVO> turnoverStatistics(LocalDate begin, LocalDate end) {
        //1.获取时间区间内的每一天的时间
        //1.1 定义一个list用来封装每一天的时间
        List<LocalDate> dateList = new ArrayList<>();

        //插入初始值
        dateList.add(begin);

        //1.3 插入第一天后的每一天的时间到list集合中
        while (!begin.equals(end)) {//只有第一天等于最后一天时循环才会结束
            begin = begin.plusDays(1);//.plusDays(1)在指定的时间家一天
            dateList.add(begin);//把每一天的日期加入list集合
        }
        //定义一个集合来封装每日营业额
        List<Double> turnoverList = new ArrayList<>();
        //查询dao获取每日营业额并封装到集合中
        dateList.forEach(date -> {
            //获取当天的最小时间,年月日时分秒 00:00
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//,of方法把LocalDate转换为LocalDateTime
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//LocalTime.MAX获取一天的最大值,MIN获取一天的最小值

            //参数用map传递
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("min", beginTime);
            map.put("max", endTime);

            //调用dao用动态sql查询每天营业额
            Double turnover = orderMapper.sumByMap(map);
            //注意,此时返回的turnover,是很有可能为空的,这里用正则表达式为null时赋值为0
            //添加结果封装到集合中
            turnoverList.add(turnover == null ? 0 : turnover);
        });

        //封装数据返回
        TurnoverReportVO vo = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();

        return Result.success(vo);
    }

    /**
     * 用户数据统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result userStatistics(LocalDate begin, LocalDate end) {
        //获取区间内每一天,封装到集合中
        List<LocalDate> dateList = new ArrayList<>();

        //设置初始值
        dateList.add(begin);//加入第一天日期

        //循环获取所有日期
        while (!begin.equals(end)) {//循环到begin=end才会结束
            begin = begin.plusDays(1);
            dateList.add(begin);//从第二天开始加到最后一天
        }

        //调用dao获取每日用户总量和新增用户量数据,并封装到集合中
        //创建集合
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();

        //循环遍历日期,查询用户总量和新增数据
        dateList.forEach(date -> {
            //获取每个日期当天最大时间和最小时间用来查询判断
            LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);//获取当天最小值
            LocalDateTime max = LocalDateTime.of(date, LocalTime.MAX);//获取最大值

            //用map结合封装
            Map map = new HashMap();
            map.put("max", max);

            //调用dao查询用户总量
            Integer totalUserCount = userMapper.userList(map);

            map.put("min", min);
            //调用dao查询当天用户新增用户
            Integer newUserCount = userMapper.userList(map);

            //封装到集合返回
            totalUserList.add(totalUserCount);
            newUserList.add(newUserCount);
        });

        UserReportVO vo = UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();


        return Result.success(vo);
    }

    /**
     * 订单数据统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result ordersStatistics(LocalDate begin, LocalDate end) {
        //获取包含的每一个日子并封装到集合中
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //循环获取每个日期
        while (!begin.equals(end)){
            begin= begin.plusDays(1);
            dateList.add(begin);
        }

        //查询每天的订单总数和有效订单数,封装进集合中
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();

        //遍历查询
        dateList.forEach(date->{
            //获取每天时间的最大值和最小值
            LocalDateTime min = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(date, LocalTime.MAX);

            //查询条件封装在map进行查询
            Map map = new HashMap();
            map.put("min",min);
            map.put("max",max);
            //查询根据最大最小时间查询当日所有订单
            Integer orderCount = orderMapper.orderCountList(map);
            map.put("status",Orders.COMPLETED);
            Integer validOrderCount = orderMapper.orderCountList(map);
            //插入集合中
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        });
        //聚合求订单总数
        Integer totalOrdersCount = orderCountList.stream().reduce(Integer::sum).get();
        //聚合求有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //订单完成率=有效订单数/总订单数
        Double orderCompletionRate = 0.0;
        if (totalOrdersCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrdersCount;
        }

        OrderReportVO vo = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList))
                .validOrderCountList(StringUtils.join(validOrderCountList))
                .totalOrderCount(totalOrdersCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

        return Result.success(vo);
    }

    /**
     * 查询指定时间区间内的销量排名top10
     * @param begin
     * @param end
     * @return
     * */
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end){
        //1.转化时间格式
        //1.1.获取当天的最小时间，年月日时分秒 00:00
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        //1.2 获取当天的最大时间，年月日时分秒 59:59
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //2.根据时间区间查询销量(订单表和订单详情表),包含菜品名称，以及对应的销量数
        List<GoodsSalesDTO> goodsSalesDTOS=orderMapper.getSalesTop10(beginTime,endTime);
        //3.获取商品名称列表
        List<String> nameList = goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        //4.获取销量列表
        List<Integer> numberList = goodsSalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        //5.返回数据
        SalesTop10ReportVO vo = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
        return vo;
    }

    /**
     * 导出近30天的运营数据报表
     *
     * @param response
     **/
    @Override
    public void exportBusinessData(HttpServletResponse response) {
    try {
        //获取今天日子,并减30天
        LocalDate begin = LocalDate.now().minusDays(30);
        //获取昨天日期不包含时分秒
        LocalDate end = LocalDate.now().minusDays(1);

        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        //查询概览运营数据，提供给Excel模板文件

        //获取模板文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        //2.获取excel文件对象
        XSSFWorkbook excel = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = excel.getSheet("Sheet1");

        //2.1 为第二行第二个单元格赋,值日期范围
        sheet.getRow(1).getCell(1).setCellValue("时间"+begin+"至"+end);

        //获得第4行
        XSSFRow row = sheet.getRow(3);
        //获取单元格
        row.getCell(2).setCellValue(businessData.getTurnover());
        row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
        row.getCell(6).setCellValue(businessData.getNewUsers());
        row = sheet.getRow(4);
        row.getCell(2).setCellValue(businessData.getValidOrderCount());
        row.getCell(4).setCellValue(businessData.getUnitPrice());
        for (int i = 0; i < 30; i++) {
            LocalDate date = begin.plusDays(i);
            //准备明细数据
            businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            row = sheet.getRow(7 + i);
            row.getCell(1).setCellValue(date.toString());
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(3).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessData.getUnitPrice());
            row.getCell(6).setCellValue(businessData.getNewUsers());
        }
        //通过输出流将文件下载到客户端浏览器中
        ServletOutputStream out = response.getOutputStream();
        excel.write(out);
        //关闭资源
        out.flush();
        out.close();
        excel.close();


    } catch (IOException e) {
            e.printStackTrace();
        }

    }


}










